#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdatomic.h>
#include "somb.h"

void run_mem_client_client_listen_method_onvailable_cb(uint32_t ServiceId,bool bAvailable)
{
    //printf("run_mem_client client listen method callback, recv serviceid=%08x is onvailbe=%d\n",ServiceId,bAvailable);

}

void run_mem_client_client_listen_event_cb(uint32_t ServiceId,void*EvtData,uint32_t EvtDataLen)
{
    //printf("run_mem_client client listen event callback, recv serviceid=%08x EvtDataLen=%d\n",ServiceId,EvtDataLen);
    //printf("event data [%s]\n", (char*)EvtData);
}

void add_listen_service(int service_num)
{
    int32_t ret;
    ST_SOMB_SERVICE_LISTEN_INFO *pstServiceListenInfo=NULL;

    pstServiceListenInfo = malloc(sizeof(ST_SOMB_SERVICE_LISTEN_INFO) * service_num);
    if(NULL == pstServiceListenInfo)
    {
        printf("malloc for %d service failed", service_num);
        return;
    }

    for(int loop=0; loop < service_num; loop++)
    {

        if (loop%2 == 0) 
        { 
            pstServiceListenInfo[loop].ServiceId= loop;
            pstServiceListenInfo[loop].ServiceType = SOMB_SVC_TYPE_METHOD;
            pstServiceListenInfo[loop].OnAvailableCB = run_mem_client_client_listen_method_onvailable_cb;
        } 
        else 
        { 
            pstServiceListenInfo[loop].ServiceId= loop;
            pstServiceListenInfo[loop].ServiceType = SOMB_SVC_TYPE_EVENT;
            pstServiceListenInfo[loop].ListenerFlags = SOMB_SVC_FLAGS_EVENT_LISTEN_SYNC_DATA; //this flags means the event data will sync to you when it is deployed by it's provider
            pstServiceListenInfo[loop].ListenerCB = run_mem_client_client_listen_event_cb;
        }

    }

    ret = i32SOMB_ServiceListener_Add(pstServiceListenInfo, service_num);
    if(0 != ret)
    {
        printf("run_mem_client service listener add failed\n");
    }
    else
    {
        printf("run_mem_client service listener add success\n");
    }

    free(pstServiceListenInfo);
}
void print_usage(void)
{
    printf("1: add listen service\n");
    printf("2: del listen service\n");
}
int main(void)
{
    uint32_t SubNsId;
    int32_t ret = i32SOMB_SubNs_Init(&SubNsId);
    if(SOMB_OK != ret)
    {
        printf("consumer somb sub ns init failed\n");
        return -1;
    }
    printf("SubNs=%d SOMB Init success\n",SubNsId);

    while(1)
    {
        print_usage();
        printf("chose your test index:\n");
        int cmd;
        scanf("%d",&cmd);
        printf("your chose is %d \n",cmd);
        switch(cmd)
        {
            case 1: /*listen service*/
            {
                int service_num;
                scanf("%d",&service_num);
                printf("your service_num is %d \n",service_num);
                add_listen_service(service_num);
            }
                break;
            case 2:
                //del_listen_service();
                break;
            default:
                break;
        }

    }

    return 0;
}
